// pages/handle/index.js
const storageService = require('../../services/storage')
import * as comm from '../../utils/common';

function isNumber(value) {
  if (value == null || value == undefined || value.length == 0) {
    return false;
  }
  return !isNaN(value);
}


// 获取 App 实例
const appInstance = getApp();
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  /**
   * 组件的属性列表
   */
  properties: {
    did: {
      type: String,
      value: ''
    },
  },
  data: {
    handCfg: {},
    deviceCfg: {},

    autoRun: 0,
    longtap: false,
    showWithInput: false,
    modeName: "",
    showWithHandSetting: false,
    timeoutObj: null,
    verObj: {
      "t": "",
      "v": 0,
      "s": ""
    },
    isHandVer: false,
    hasTempSync: false,
  },

  lifetimes: {
    attached() {
      console.log("attached....................hand");
      let autoRunCfg =  storageService.getAutoRunCfg(this.data.did)
      this.setData({
        autoRun: comm.isEmptyObj(autoRunCfg) ? 0 : autoRunCfg.sRun
      });
      let dobj = storageService.getDeviceInfo(this.data.did)
      this.data.deviceCfg = dobj;

      let tvobj = appInstance.deviceVerMap[this.data.did];
      if (!comm.isEmptyObj(tvobj)) {
        this.verObj = JSON.parse(JSON.stringify(tvobj));
        this.setData({
          isHandVer: (this.verObj.t == "C")
        });
      }
      let tempSync = storageService.getTmpSynced(this.data.did)
      this.hasTempSync = !comm.isEmpty(tempSync);
      this.getAndInitChs();
    },
  },
  methods: {
    getAndInitChs() {
      let handCfg = storageService.getHandCfg(this.data.did)
      if (comm.isEmptyObj(handCfg)) {
        let chCfg = storageService.getDeviceChannels(this.data.did)
        handCfg = {
          sel: 0,
          handM: 30,
          modes: [{
              "nm": this.data.isHandVer ? "手动模式" : "模式一",
              "cls": []
            },
            {
              "nm": this.data.isHandVer ? "临时开灯" : "模式二",
              "cls": []
            }
          ]
        };
        for (var j = 0; j < handCfg.modes.length; j++) {
          let cls = handCfg.modes[j].cls;
          for (var i = 0; i < chCfg.length; i++) {
            if (chCfg[i].u == 0) {
              continue;
            }
            cls.push({
              "n": chCfg[i].n,
              "nm": chCfg[i].nm,
              "c": chCfg[i].c,
              "v": 0
            });
          }
        }
        storageService.saveHandCfg(this.data.did, handCfg)
      }
      if (this.data.isHandVer && handCfg.modes[0].nm != "手动模式") { //兼容老版本
        handCfg.modes[0].nm = "手动模式";
        handCfg.modes[1].nm = "临时开灯";
        handCfg.handM = 30;
        storageService.saveHandCfg(this.data.did, handCfg)
      }
      this.setData({
        handCfg: JSON.parse(JSON.stringify(handCfg))
      });
      console.log(this.data.handCfg);
    },
    sliderChange(e) {
      if (this.valChange(e)) {
        storageService.saveHandCfg(this.data.did, this.data.handCfg)
        this.sendValChgMsg(e);
      }
    },
    sliderChangeing(e) {
      this.valChange(e);
    },
    steppperChange(e) {
      if (this.valChange(e)) {
        storageService.saveHandCfg(this.data.did, this.data.handCfg)
        this.sendValChgMsg(e);
      }
    },
    valChange(e) {
      if (this.data.isHandVer) {
        if (this.data.autoRun == 1 && this.data.handCfg.sel == 0) {
          this.showToast("自动模式下无法手动调整!");
          return false;
        }
      } else {
        if (this.data.autoRun == 1) {
          this.showToast("自动模式下无法手动调整!");
          return false;
        }
      }

      if (this.data.handCfg.sel < 0) {
        this.showToast("请先选择模式!");
        return false;
      }
      const {
        value
      } = e.detail;
      let idx = e.currentTarget.dataset.idx;
      let str = "handCfg.modes[" + this.data.handCfg.sel + "].cls[" + idx + "].v";
      this.setData({
        [str]: value
      });
      return true;
    },
    sendValChgMsg(e) {
      if (this.data.isHandVer && this.data.handCfg.sel == 1) {
        return;
      }
      const {
        value
      } = e.detail;
      let idx = e.currentTarget.dataset.idx;
      appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgVal", {
        n: this.data.handCfg.modes[this.data.handCfg.sel].cls[idx].n,
        v: value
      });
    },
    selMode(e) {
      if (!this.data.isHandVer) {
        if (this.data.longtap) {
          this.data.longtap = false;
          return;
        }
      }

      let idx = e.currentTarget.dataset.idx;
      if (this.data.handCfg.sel == idx) {
        return;
      }
      this.setData({
        "handCfg.sel": idx
      });
      storageService.saveHandCfg(this.data.did, this.data.handCfg)
    },
    editModeName() {
      if (this.data.isHandVer) {
        return;
      }
      this.data.longtap = true;
      this.setData({
        showWithInput: true,
        modeName: this.data.handCfg.modes[this.data.handCfg.sel].nm
      });
    },
    editConfirm() {
      if (comm.isEmpty(this.data.modeName)) {
        this.showToast("名称不能为空!");
        this.setData({
          modeName: this.data.handCfg.modes[this.data.handCfg.sel].nm
        });
        return;
      }
      let str = "handCfg.modes[" + this.data.handCfg.sel + "].nm";
      this.setData({
        [str]: this.data.modeName
      });
      storageService.saveHandCfg(this.data.did, this.data.handCfg)
      this.closeDialog();
    },
    closeDialog() {
      this.setData({
        showWithInput: false
      });
    },
    bindKeyInput: function (e) {
      let val = e.detail.value;
      if (comm.isEmpty(val)) {
        val = "";
      }
      this.setData({
        modeName: val
      })
    },
    confirmPopSyncToDeviceDialogResult(succ) {
      const $t = this;
      wx.hideLoading();
      if (succ == 0) {
        $t.showToast("请求响应超时...");
      } else {
        $t.showToast("同步成功!");
        clearTimeout($t.data.timeoutObj);
        storageService.setTmpSynced(this.data.did)
        $t.hasTempSync = true;
      }
    },
    handOn() {
      if (!this.hasTempSync) {
        this.showToast("请先同步临时配置到设备...");
        return;
      }
      appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "handOn", null);
      this.showToast("命令已发送...");
    },
    handOff() {
      if (!this.hasTempSync) {
        this.showToast("请先同步临时配置到设备...");
        return;
      }
      appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "handOff", null);
      this.showToast("命令已发送...");
    },
    handCanel() {
      appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "handCanel", null);
      this.showToast("命令已发送...");
    },
    handSetting() {
      this.setData({
        showWithHandSetting: true,
        "handCfg.handM": this.data.handCfg.handM
      });

    },
    confirmHandDialog() {
      let cls = this.data.handCfg.modes[1].cls;
      let flag = true;
      for (var i = 0; i < cls.length; i++) {
        if (cls[i].v != 0) {
          flag = false;
          break;
        }
      }
      if (flag) {
        this.showToast("临时开灯灯光强度配置不能全为0!");
        return;
      }
      this.closeHandDialog();
      const $t = this;
      wx.showLoading({
        title: 'Loading......',
        mask: true,
        success: function () {
          let obj = {
            "handM": $t.data.handCfg.handM
          };
          let vArr = [];
          let cls = $t.data.handCfg.modes[1].cls;
          for (var i = 0; i < cls.length; i++) {
            vArr.push(cls[i].v);
          }
          obj.tl = vArr;
          console.log(obj);
          appInstance.sendMtMsg($t.data.deviceCfg.topicSend, "syncHandUp", obj);
          $t.data.timeoutObj = setTimeout(function () {
            $t.confirmPopSyncToDeviceDialogResult(0);
          }, 5000);
        }
      });
    },
    closeHandDialog() {
      this.setData({
        showWithHandSetting: false
      });
    },
    bindKeyHandMInput: function (e) {
      let val = e.detail.value;
      if (comm.isEmpty(val)) {
        return;
      }
      if (!isNumber(val)) {
        val = 0;
      } else {
        val = parseInt(val);
      }
      if (val < 1 || val > 999) {
        this.setData({
          "handCfg.handM": this.data.handCfg.handM
        });
      } else {
        this.setData({
          "handCfg.handM": val
        });
        storageService.saveHandCfg(this.data.did, this.data.handCfg)
      }
    },
    handAllOn() {
      if (this.data.autoRun == 1) {
        return;
      }
      let vArr = [];
      let cls = this.data.handCfg.modes[this.data.handCfg.sel].cls;
      for (var i = 0; i < cls.length; i++) {
        vArr.push({
          "n": cls[i].n,
          "v": 100
        });
      }
      appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgValAll1", vArr);
      this.showToast("命令已发送...");
    },
    handAllConfig() {
      if (this.data.autoRun == 1) {
        return;
      }
      let vArr = [];
      let cls = this.data.handCfg.modes[this.data.handCfg.sel].cls;
      for (var i = 0; i < cls.length; i++) {
        vArr.push({
          "n": cls[i].n,
          "v": cls[i].v
        });
      }
      appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgValAll1", vArr);
      this.showToast("命令已发送...");
    },
    handAllOff() {
      if (this.data.autoRun == 1) {
        return;
      }
      appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgValAll0", null);
      this.showToast("命令已发送...");
    },


    showToast(msg) {
      // 子组件中
      this.triggerEvent('showToast', {
        msg: msg
      });
    },
  },
})